package  com.baomidou.springwind.controller;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.framework.common.util.DateUtil;
import com.baomidou.framework.controller.SuperController;
import com.baomidou.framework.upload.UploadFile;
import com.baomidou.framework.upload.UploadMsg;
import com.baomidou.framework.upload.UploadMultipartRequest;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.springwind.common.HoorayosHelper;
import com.baomidou.springwind.entity.App;
import com.baomidou.springwind.entity.AppCategory;
import com.baomidou.springwind.entity.Member;
import com.baomidou.springwind.entity.MemberApp;
import com.baomidou.springwind.entity.MyPermission;
import com.baomidou.springwind.service.IAppCategoryService;
import com.baomidou.springwind.service.IAppService;

/**
 *  应用市场控制器首页
 * @author koumiba
 * @Date 2016-04-13
 */
@Controller
@RequestMapping("/sysapp/appmarket")
public class MarketController extends SuperController {
	@Autowired
	private IAppService appService;
	@Autowired
	private IAppCategoryService appCategoryService;
	/**
	 * 主页
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/index")
	public String index(Model model) {
		// 获取符合条件的App
		App app = new App();
		EntityWrapper ew = new EntityWrapper(new App());
		ew.where("isrecommend=1");
		App recommandApp = app.selectOne(ew);
		model.addAttribute("recommendApp", recommandApp);
		int mid = HoorayosHelper.getMemberId(request);		
		Boolean isLogin = HoorayosHelper.checkLogin(request);
		
		// 获取用户相关信息
		Member member = new Member(); 
		Member user = member.selectById(mid);
		model.addAttribute("isLogin",isLogin.toString());
		model.addAttribute("type", user==null ? "" : user.getType());
		if(isLogin ){
			// 获取当前用户APP列表（仅限realid列）
			ew = new EntityWrapper(new MemberApp());
			ew.setSqlSelect("realid");
			ew.and("member_id="+mid);
			List myappList = new ArrayList<String>();
			for(MemberApp ma : new MemberApp().selectList(ew)){
				myappList.add(ma.getRealid());
				if(ma.getRealid() == recommandApp.getTbid()){
					model.addAttribute("recommendAppIsinstalled", 1);
				}
			}
			model.addAttribute("myappList", myappList);
			// 获取当前用户APP列表（仅限realid和tbid列），且realid不为空
			ew = new EntityWrapper(new MemberApp());
			ew.setSqlSelect("tbid,realid").where("member_id="+mid+" AND realid is not null");
			List<MemberApp> temp  = new MemberApp().selectList(ew);
			Map<Integer,Integer> myappList2 = new HashMap<Integer,Integer>();
			for(MemberApp ma : temp){
				myappList2.put(ma.getRealid().intValue(),ma.getTbid().intValue()); 
				if(ma.getRealid() == recommandApp.getTbid()){
					model.addAttribute("recommendAppId",ma.getTbid().intValue());
				}
			}
			model.addAttribute("myappList2", myappList2);
			// 获取当前用户被审核的应用数量
			model.addAttribute("user", user);
			ew = new EntityWrapper(new App());
			ew.where("member_id="+mid+" AND verifytype=1");
			model.addAttribute("myappcount", app.selectCount(ew));
			// 获取挡墙用户未被审核的应用数量
			ew = new EntityWrapper(new App());
			ew.where("member_id="+mid+" AND verifytype<>1");
			model.addAttribute("myappunverifycount", app.selectCount(ew));
		}
		
		// 获取APP属性列表
		AppCategory appCategory = new AppCategory();
		List<AppCategory> acList = appCategory.selectAll();
		model.addAttribute("acList", acList);
		
		return "sysapp/market/index";
	}
	
	/**
	 * ajax页面
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/ajax")
	public String ajax() {
		String display; //需要在html页面上显示的内容
		Integer search_1 = request.getParameter("search_1")=="" ? 0 : Integer.parseInt(request.getParameter("search_1"));
		Integer search_2 = request.getParameter("search_2")=="" ? 0 : Integer.parseInt(request.getParameter("search_2"));
		String search_3 = request.getParameter("searche_3");
		Integer from = Integer.parseInt(request.getParameter("from"));
		Integer to = Integer.parseInt(request.getParameter("to"));
		int mid = HoorayosHelper.getMemberId(request);
		EntityWrapper ew = new EntityWrapper(new MemberApp());
		ew.setSqlSelect("realid").and("member_id="+mid);
		List<MemberApp> myappList = new MemberApp().selectList(ew);
		
		ew = new EntityWrapper(new MemberApp());
		ew.setSqlSelect("tbid,realid").where(" member_id="+mid+" AND realid is not null");
		List<MemberApp> temp  = new MemberApp().selectList(ew);
		Map<Integer,Integer> myappList2 = new HashMap<Integer,Integer>();
		for(MemberApp ma : temp){
			myappList2.put(ma.getRealid().intValue(),ma.getTbid().intValue()); 
		}		
		EntityWrapper<App> appWrapper = new EntityWrapper<App>(new App());
		if(!HoorayosHelper.checkLogin(request) || !checkAdmin()){
			ew = new EntityWrapper(new AppCategory());
			ew.setSqlSelect("tbid").where("issystem=0");
			List<AppCategory> acList = (new AppCategory()).selectList(ew);
			List<Integer> categoryIds = new ArrayList<Integer>();
			for(AppCategory ac : acList){
				categoryIds.add(ac.getTbid().intValue());
			}
			appWrapper.in("app_category_id",categoryIds);
		}
		if(search_1 != 0){
				//查询挂件应用
				if(search_1 == -1){
					appWrapper.and("type='widget'");
				}
				//查询已安装的应用
				else if(search_1 == -2){
					if(myappList != null && myappList.size()>0 ){
						List<Integer> myappTbids = new ArrayList<Integer>();
						for(MemberApp ma : myappList){
							myappTbids.add(ma.getRealid().intValue()); 
						}
						appWrapper.in("tbid",myappTbids);
					}else{
						appWrapper.and("tbid=0");
					}
				}
				//根据所选应用分类查询应用
				else{
					appWrapper.and("app_category_id="+search_1);
					//如果是系统分类，则只显示可添加的系统应用
					ew = new EntityWrapper<AppCategory>();
					ew.setSqlSelect("issystem").and("tbid="+search_1);
					
					if(new AppCategory().selectOne(ew).getIssystem()==1){
						if(checkAdmin()){
							ew = new EntityWrapper<Member>();
							ew.and("tbid="+mid);
							String permissionId = new Member().selectOne(ew).getPermissionId().toString();
							if(permissionId != ""){
								ew = new EntityWrapper<Permission>();
								String appsId = new MyPermission().selectOne(ew.and("tbid="+permissionId)).getAppsId();
								
								if(appsId != ""){
									appWrapper.and("tbid in ("+appsId+")");
								}
							}else{
								appWrapper.and("tbid=null");
							}
						}else{
							appWrapper.and("tbid=null");
						}
					}
				}
			}
			if(search_3 != ""){
				appWrapper.like("name", search_3);
			}
			appWrapper.and("verifytype=1");
			display = new App().selectCount(appWrapper)+"<{|*|}>";
			if(search_2 == 1){
					appWrapper.orderBy("dt", false);				
			}else if(search_2 == 2){
					appWrapper.orderBy("usecount", false);
			}else if(search_2 == 3){	
					appWrapper.orderBy("starnum", false);
			}
			List<App> appListTemp = new App().selectList(appWrapper);
			List<App> appList =  new ArrayList<App>();
			for(int i=from; i<= from+to; i++){
				if(i >= appListTemp.size()) break;
				appList.add(appListTemp.get(i));
			}			
			if(appList.size() > 0){
				for(App app : appList){
					Double starNum = app.getStarnum();
					Boolean starnumIsInt = true;
					if(starNum-starNum.intValue()>0){
						starnumIsInt = false;
					}
					display += "<li><a href='javascript:openDetailIframe2(\'detail.html?id="+app.getTbid()+"\');'>"
							+ "<img src='"+app.getIcon()+"'></a>"
									+ "<a href='javascript:openDetailIframe2(\'detail.php?id="+app.getTbid()+"\');' class='app-name'>"+app.getName()+"</a>"
											+ "<span class='app-desc'>"+app.getRemark()+"</span>"
											+ "<span class='star-box'><i style='width:"+(app.getStarnum() * 20)+"%;'></i></span>"
											+ "<span class='star-num'>"+ ( starnumIsInt || app.getStarnum() == 0 ? app.getStarnum().intValue() : new DecimalFormat("0.0").format(app.getStarnum()))+"</span>"
											+ "<span class='app-stat'>"+app.getUsecount()+" 人正在使用</span>";
					List<Integer> myappTbidList = new ArrayList<Integer>();
					for(MemberApp ma : myappList){
						myappTbidList.add(ma.getRealid().intValue());
					}
					if(myappTbidList.contains(app.getTbid().intValue())){
						if(search_1 == -2){
							display += "<a href='javascript:;' app_id='"+myappList2.get(app.getTbid().intValue())+"' real_app_id='"+app.getTbid()+"' app_type='"+app.getType()+"' class='btn-run-s' style='right:35px' title='打开应用'>打开应用</a>";
							display += "<a href='javascript:;' app_id='"+myappList2.get(app.getTbid().intValue())+"' real_app_id='"+app.getTbid()+"' app_type='"+app.getType()+"' class='btn-remove-s' style='right:10px' title='删除应用'>删除应用</a>";
						}else{
							display += "<a href='javascript:;' app_id='"+myappList2.get(app.getTbid().intValue())+"' real_app_id='"+app.getTbid()+"' app_type='"+app.getType()+"' class='btn-run-s' title='打开应用'>打开应用</a>";
						}
					}else{
						display += "<a href='javascript:;' real_app_id='"+app.getTbid()+"' class='btn-add-s' title='添加应用'>添加应用</a>";
					}
					display += "</li>";
				}
			}
		return display;
	}
	
	/**
	 * 我的应用管理页
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/myappmanage")
	public String myappManage(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		EntityWrapper ew = new EntityWrapper<AppCategory>();
		model.addAttribute("appCategoryList", appCategoryService.selectList(ew));
		model.addAttribute("issetAdd", request.getAttribute("add")!=null);
		
		return "sysapp/market/myappmanage";
		
	}
	
	/**
	 * 我的应用编辑页
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/myappedit")
	public String myappEdit(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		
		String appid = request.getParameter("appid");
		Map<String, Object> app = new HashMap<String, Object>();
		
		if(appid==null || appid == ""){
			app.put("type", "window");
			app.put("isresize", 1);
			app.put("isopenmax", 0);
			app.put("isflash", 0);
			app.put("verifytype", 0);
		}else{
			App appObject = appService.selectById(appid);
			app.put("name", appObject.getName());
			app.put("url", appObject.getUrl());
			app.put("width", appObject.getWidth());
			app.put("height", appObject.getHeight());
			app.put("verifyinfo", appObject.getVerifyinfo());
			app.put("type", appObject.getType());
			app.put("icon", appObject.getIcon());
			app.put("isresize", appObject.getIsresize());
			app.put("isopenmax", appObject.getIsopenmax());
			app.put("isflash", appObject.getIsflash());
			app.put("verifytype", appObject.getVerifytype());
			app.put("app_category_id", appObject.getAppCategoryId().intValue());
		}
		model.addAttribute("appid", appid);
		model.addAttribute("app", app);
		
		/*
		 * 获取category名
		 */
		if((Integer)app.get("verifytype") == 1 || (Integer)app.get("verifytype") == 2){
			AppCategory ac = appCategoryService.selectById((Integer)app.get("app_category_id"));
			model.addAttribute("categoryName", ac.getName());
		}else{
			EntityWrapper ew = new EntityWrapper<AppCategory>();
			ew.where("issystem=0");
			List<AppCategory> appCategoryList = new AppCategory().selectList(ew);
			model.addAttribute("categoryList", appCategoryList);		
			
		}
		
		return "sysapp/market/myappedit";
	}
	
	/**
	 * ajax页面
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/myappajax")
	public String myappAjax(Model model) {
		String ac  = request.getParameter("ac");
		String search1  = request.getParameter("search_1");
		String search2  = request.getParameter("search_2");
		String search3  = request.getParameter("search_3");
		String search4  = request.getParameter("search_4");
		
		int mid = HoorayosHelper.getMemberId(request);
		EntityWrapper ew = new EntityWrapper<App>();
		String display = "";
		
		if(ac.equals("getList")){
			List<AppCategory> appCategoryList = new AppCategory().selectAll();
			Map<Integer, String> category = new HashMap<Integer,String>();
			for(AppCategory appc : appCategoryList){
				category.put(appc.getTbid().intValue(), appc.getName());
			}
			
			ew.and("member_id="+mid);
			if(search1 != null && !search1.equals("")){
				ew.like("name", search1);
			}
			if(search2 != null && !search2.equals("")){
				ew.and("app_category_id="+search2);
			}
			if(search3 != null && !search3.equals("")){
				ew.and("type='"+search3+"'");
			}
			ew.and("verifytype="+search4);
			List<App> appList = new App().selectList(ew);
			
			display = appList.size() + "<{|*|}>";
			int from = Integer.parseInt(request.getParameter("from"));
			int to = Integer.parseInt(request.getParameter("to"));
			int index = 1;
			for(App v : appList){
				if(index<from || index>=to) break;
				index ++;
				display += "<tr class='list-bd'>";
				display += "<td style='text-align:left;padding-left:15px'><img src='"+v.getIcon()+"' alt='"+v.getName()+"' class='appicon'><span class='appname'>"+v.getName()+"</span></td>";
				display += "<td>"+(v.getType().equals("window") ? "窗口" : "挂件")+"</td>";
				display += "<td>"+(v.getAppCategoryId() == 0 ? "未分类" : category.get(v.getAppCategoryId().intValue()))+"</td>";
				display += "<td>"+v.getUsecount()+"</td>";
				display += "<td>";
				display += "<a href='javascript:openDetailIframe(\"myappedit.html?appid="+v.getTbid()+"\");' class='btn btn-mini btn-link'>详情</a>";
				display += "</td>";
				display += "</tr>";
			}
			return display;
		}else if(ac.equals("edit")){
			App data = new App();
			data.setIcon(request.getParameter("val_icon"));
			data.setName(request.getParameter("val_name"));
			data.setAppCategoryId(Long.parseLong(request.getParameter("val_app_category_id")));
			data.setUrl(request.getParameter("val_url"));
			data.setWidth(Integer.parseInt(request.getParameter("val_width")));
			data.setHeight(Integer.parseInt(request.getParameter("val_height")));
			data.setIsresize(Integer.parseInt(request.getParameter("val_isresize")));
			data.setIsopenmax(Integer.parseInt(request.getParameter("val_isopenmax")));
			data.setIssetbar(1);
			data.setIsflash(Integer.parseInt(request.getParameter("val_isflash")));
			data.setRemark(request.getParameter("val_remark"));
			
			String id = request.getParameter("id");
			if("".equals(id)){
				// 获取最新的一个appid
				ew = new EntityWrapper<App>();
				ew.orderBy("tbid", false);
				App lastApp = new App().selectOne(ew);
				long nextAppId = (lastApp==null ? 1 : lastApp.getTbid()+1);
				data.setTbid(nextAppId);
				data.setType(request.getParameter("val_type"));
				data.setDt(new Date());
				data.setVerifytype(0);
				data.setMemberId((long)mid);
				appService.insert(data);
			}else{
				data.setVerifytype(2);
				data.setTbid(Long.parseLong(id));
				data.setMemberId((long)mid);
				appService.insertOrUpdate(data);
			}
			Map result = new HashMap<String, String>();
			result.put("info", "");
			result.put("status", "y");
			return JSONUtils.toJSONString(result);
		}else if(ac.equals("del")){
			ew = new EntityWrapper<App>();
			ew.where("tbid="+request.getParameter("appid")+" AND member_id="+mid);
			appService.delete(ew);
			
		}else if(ac.equals("uploadImg")){
			UploadMsg msg = new UploadMsg();
			try {
				UploadMultipartRequest umr = new UploadMultipartRequest(request, getSaveDir(), 2048000);
//				umr.setFileHeaderExts("ffd8ff.jpg");
				umr.upload();
				Enumeration<?> files = umr.getFileNames();
				while ( files.hasMoreElements() ) {
					String name = (String) files.nextElement();
					UploadFile cf = umr.getUploadFile(name);
					if ( cf != null ) {
						Map<String, String> info = new HashMap<String, String>();
						info.put("url", getSurlPath()+cf.getFilename());
						info.put("fileType", cf.getType());
						info.put("original", cf.getOriginalFileName());
						info.put("state", cf.getUploadCode().key()+"");
						return JSONUtils.toJSONString(info);
					}
				}
			}catch ( IOException e ) {
				logger.error("uploadFile error. ", e);
			}	
		}
		return "";
	}
	/*************************
	 *    私有方法 
	 *************************/
	
	
	/**
	 * 验证是否为管理员
	 * @return Boolean
	 * koumiba
	 * 2017年3月26日
	 */
	private Boolean checkAdmin(){
		int mid = HoorayosHelper.getMemberId(request);
		EntityWrapper ew = new EntityWrapper(new Member());
		Member m = new Member().selectById(mid);
		return m.getType() == 1 ? true : false;
	}
	/**
	 * <p>
	 * 上传文件存放目录 uploads/shortcut/{yyyy}{mm}{dd}/{time}{rand:6}
	 * </p>
	 */
	private String getSaveDir() {
		StringBuffer filePath = new StringBuffer(session.getServletContext().getRealPath("/"));
		filePath.append(File.separator).append("WEB-INF").append(File.separator).append("static")
		.append(File.separator).append("uploads").append(File.separator).append("shortcut").append(File.separator);
		filePath.append(DateUtil.format(new Date(), "yyyyMMdd"));
		File file = new File(filePath.toString());
		if ( !file.exists() ) {
			file.mkdirs();
		}
		
		return file.getPath();
	}
	/**
	 * 获取图片的web访问路径
	 * @return String
	 * koumiba
	 * 2017年4月8日
	 */
	private String getSurlPath(){
		return "/static/uploads/shortcut/"+DateUtil.format(new Date(), "yyyyMMdd")+"/";
	}
}
